package http;

import cn.hutool.core.lang.Assert;

import java.net.HttpURLConnection;
import java.net.URL;

public class UrlAvailability {

    /**
     * 功能描述 : 检测当前URL是否可连接或是否有效, 最多连接网络 5 次, 如果 5 次都不成功说明该地址不存在或视为无效地址.
     * @param url 指定URL网络地址
     * @return String
     */
    public static Integer isConnect(String url) {
        Assert.notBlank(url);
        int counts = 0, in = 0;
        while (counts < 5) {
            try {
                URL httpUrl = new URL(url);
                HttpURLConnection connection = (HttpURLConnection) httpUrl.openConnection();
                int state = connection.getResponseCode();
                if (state == 200) {
                    in = 1;
                }
                break;
            } catch (Exception ex) {
                counts++;
                continue;
            }
        }
        return in;
    }
}
